// pages/cardDetails/cardDetails.js 
const innerAudioContextRecord = wx.createInnerAudioContext();  //创建录音音频对象
const innerAudioContext = wx.createInnerAudioContext();  //创建音频对象
innerAudioContextRecord.autoplay = true;
innerAudioContext.loop = true;
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    position:'',
    animationData:'',
    over:true,
    musicStatus: false,  //音乐是否播放
    share: true,
    avatar: '',
    nickName: '',
    month: '',
    day: '',
    open:false,
    packet:false,   //hb弹窗状态
    goldenPig: false,   //金猪弹窗状态
    hasPig: false,   //是否领取到金猪
    info:[],
    resivemoney:0,
    status:true,
    tologin:true,
    hasphone:false,
    bgimg: '../../img/bg.jpg',
    iscompany:0,
  },
  tocominfo: function (e) {
    wx.navigateTo({
      url: '/pages/company/company?cardid=' + this.data.id,
    })
  },
  // musicHandle
  musicHandle(e) {
    let that = this;
    let musicStatus = that.data.musicStatus;
    if (musicStatus) {
      innerAudioContext.pause();
      innerAudioContext.onPause(() => {
        console.log('暂停播放');
        that.setData({
          musicStatus: false
        })
      })
    } else {
      innerAudioContext.play();
      innerAudioContext.onPlay(() => {
        console.log('开始播放');
        that.setData({
          musicStatus: true
        })
      })
    }
  },
  // 播放音频
  audioCard: function () {
    let that = this;
    that.setData({
      musicStatus: false
    }, () => {
      innerAudioContext.stop()
      innerAudioContextRecord.play()
    })
  },
  closeGoldenPig:function(){
    this.setData({
      goldenPig:false,
    })
  },
  onGotUserInfo: function () {
    var that = this;
    app.onGotUserInfo();
    that.setData({
      tologin: true,
      status: false
    })
    app.siteinfo.islogin = true;
  },
  // 获取手机号
  getPhoneNumber: function (e) {
    var that = this;
    var phone = app.siteinfo.userinfo.phone
    console.log('hasphone')
    wx.checkSession({
      success: function () {

        var ency = encodeURIComponent(e.detail.encryptedData);
        var iv = e.detail.iv;
        var sessionk = wx.getStorageSync('sessionkey');

        if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {

        } else {//同意授权
          wx.request({
            method: "GET",
            url: app.siteinfo.rootpath + 'getphonenumber',
            data: {
              uid: app.siteinfo.userinfo.id,
              encryptedData: ency,
              iv: iv,
              sessionkey: sessionk
            },
            success: (res) => {
              console.log(res);
              var phone = res.data.phone;
              app.siteinfo.userinfo.phone = phone
              console.log(phone);
              that.setData({
                hasphone: true
              })
              that.openHandle();
              
            }, fail: function (res) {
              console.log("解密失败~~~~~~~~~~~~~");
              console.log(res);
            }
          });
        }
      },
      fail: function () {
        console.log("session_key 已经失效，需要重新执行登录流程");
        that.wxlogin(); //重新登录
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    
    that.setData({
      tologin: app.siteinfo.islogin
    })
    var status = that.data.status
    var tologin = that.data.tologin
    if (!tologin) {
      that.setData({
        status: true
      })
      return;
    }
    if (app.siteinfo.userinfo.phone) {
      that.setData({
        hasphone: true,
      })
    }
    
    
    var id = options.id;
    if (id) {
      that.setData({
        id: id
      })
      wx.request({
        url: app.siteinfo.rootpath + 'gethk_over',
        data: { id: id,uid:app.siteinfo.userinfo.id,flag:'resive','shareid':options.shareid },
        success: function (res) {
          console.log(res)
          if (res.data.code != 500) {
            setTimeout(function () {
              that.getHeight()
            }, 10000);
            console.log(res.data.info);
            that.setData({
              over : true
            })
            var content = res.data.info.zhufu.split("@#$");
            console.log(content)
            if (content[0]) {
              that.setData({
                greet: content,
              })
            } else {
              that.setData({
                greet: content[0],
              })
            }


            that.setData({
              avatar: res.data.info.logo,
              nickName: res.data.info.username,
              bgimg: res.data.info.bgimg,
              info: res.data.info,
              iscompany: res.data.iscompany,
            })
            innerAudioContext.src = res.data.info.music; // 设置音频地址
            innerAudioContextRecord.src = res.data.info.audio; // 设置音频地址
            innerAudioContext.onPlay(() => {
              console.log('开始播放')
            })
            innerAudioContext.onError((res) => {
              console.log(res.errMsg)
              console.log(res.errCode)
            })
            if (innerAudioContextRecord.src) {
              that.setData({
                hasaudio: false
              })
              innerAudioContextRecord.onPlay(() => {
                console.log('录音开始播放')
              })
              innerAudioContextRecord.onError((res) => {
                console.log(res.errMsg)
                console.log(res.errCode)
              })
              innerAudioContextRecord.onEnded((res) => {
                console.log('录音播放结束')
                that.setData({
                  musicStatus: true
                }, () => { innerAudioContext.play() })
              })
            } else {
              that.setData({
                musicStatus: true,
                hasaudio: false
              }, () => { innerAudioContext.play() })
            }
            // 获取系统时间
            var myDate = new Date();
            let monthNew = myDate.getMonth()
            let dayNew = myDate.getDate()
            var month = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
            that.setData({
              month: month[monthNew],
              day: dayNew
            })

          if (res.data.code == 205) {
            wx.showToast({
              title: '该贺卡今日次数已领完',
              icon: "none"
            })
            return;
          } else if (res.data.code == 206) {
            wx.showToast({
              title: '该贺卡暂无次数，请转发',
              icon: "none"
            })
            return;
          }


            if(res.data.info.money>0){
              // 10秒之后弹出hb
              setTimeout(function () {
                that.setData({
                  packet: true
                })
              }, 12000)
            }
            if (res.data.info.pignum > 0) {
              if(res.data.info.pigimg != 1){
                that.setData({
                  hasPig: true
                })
              }else{
                that.setData({
                  hasPig: false
                })
              }
              // 10秒之后弹出hb
              setTimeout(function () {
                that.setData({
                  goldenPig: true
                })
              }, 12000)
            }
            
          }  else {
            wx.switchTab({
              url: '/pages/index/index',
            })
          }
        }
      })
    }

    
  },
  // 返回
  indexHandle: function () {
    innerAudioContext.stop()
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  // 发送朋友
  sendFriends: function () {
    innerAudioContext.stop()
    let share = this.data.share
    this.setData({
      share: false
    })
  },
  // 点击阴影
  closeHandle: function () {
    let share = this.data.share
    this.setData({
      share: true
    })
  },
  actionSheetbindchange: function () {
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    })
  },
  // 生成卡片
  postersHandle: function () {
    let share = this.data.share
    this.setData({
      share: true
    })
    wx.navigateTo({
      url: '/pages/posters/posters',
    })
  },
  //开hb
  openHandle: function () {
    let that  = this
    let { open } = that.data
    wx.request({
      url: app.siteinfo.rootpath +'resivecommoncard',
      data:{id:that.data.id,uid:app.siteinfo.userinfo.id},
      success:function(res){
        that.setData({
          resivemoney: res.data.resivemoney,
          open: true
        })
      }
    })
  },
  //关闭hb弹窗
  closePacket: function () {
    let that = this
    let { packet } = that.data
    that.setData({
      packet: false
    })
  },
  // 查看hb详情
  packetList: function () {
    wx.redirectTo({
      url: '/pages/packetList/packetList',
    })
  },

  util: function (obj) {
    console.log(obj);
    console.log(-obj.list);
    var continueTime = (parseInt(obj.list / obj.container) + 1) * 8000;
    var setIntervalTime = 200 + continueTime;

    var animation = wx.createAnimation({
      duration: 200,  //动画时长
      timingFunction: "linear", //线性
      delay: 0  //0则不延迟
    });
    this.animation = animation;
    animation.translateY(obj.container).step({ duration: 200, timingFunction: 'step-start' }).translateY(-obj.list + 10).step({ duration: continueTime });
    this.setData({
      animationData: animation.export()
    }) 
    setInterval(() => {
      animation.translateY(obj.container).step({ duration: 200, timingFunction: 'step-start' }).translateY(-obj.list + 10).step({ duration: continueTime });
      this.setData({
        animationData: animation.export()
      })
    }, setIntervalTime)
  },
  getHeight() {
    var obj = new Object();
    //创建节点选择器
    var query = wx.createSelectorQuery();
    query.select('.greeting_wrap').boundingClientRect()
    query.select('.text').boundingClientRect()
    query.exec((res) => {
      obj.container = res[0].height; // 框的height
      obj.list = res[1].height; // list的height
      // return obj;
      console.log(obj.container)
      console.log(obj.list)
      this.util(obj);
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    var position = wx.getStorageSync('position');
    that.setData({
      position: position
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    
    that.setData({
      tologin: app.siteinfo.islogin
    })
    var status = that.data.status
    var tologin = that.data.tologin
    if (!tologin) {
      if (!status) {
        that.setData({
          status: true
        })

      }
      return;
    }

    wx.request({
      url: app.siteinfo.rootpath + 'reply',
      data: { id: that.data.id, uid: app.siteinfo.userinfo.id },
      success: function (res) {

      }
    })

    let share = this.data.share
    this.setData({
      share: true
    })
    var title = app.siteinfo.userinfo.wechat_name + '给你送来了一份祝福';
    var path = '/pages/preview/preview?cardtype=common&id=' + this.data.id + '&shareid=' + app.siteinfo.userinfo.id;
    var bgimg = this.data.bgimg
    return {
      title: title,
      path: path,
      imageUrl: bgimg,
      success(e) {
        console.log()
      }
    }
    
  }
})